<!DOCTYPE html>
<html>

<head>
    <title>略略略</title>
    <script src="./adapter-latest.js"></script>
    <script>
        window.onload = async function () {
            var v_track;
            var a_track;
            document.getElementById('start').addEventListener('click', async (e) => {
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: true
                })
                const videoTracks = stream.getVideoTracks();
                v_track = videoTracks[0];
                const audioTracks = stream.getAudioTracks();
                a_track = audioTracks[0];
                connection.addStream(stream);
                document.getElementById('local_video').srcObject = stream;
            });
            document.getElementById('stop').addEventListener('click', async (e) => {
                v_track?.stop();
                a_track?.stop();
            });

            const configuration = {
                iceServers: [{ urls: 'turn:192.168.100.163:3478', username: 'simon', credential: '123456' }]
            }

            connection = new RTCPeerConnection(configuration);
            connection.onaddstream = event => {
                console.log('onaddstream', event);
                document.getElementById('remote_video').srcObject = event.stream
            }
            connection.oniceconnectionstatechange = event => {
                console.log('ICE connection state change: ', connection.iceConnectionState);
            };

            connection.onicecandidate = event => {
                console.log('onicecandidate', event);
                if (event.candidate) {
                    sendMessage({
                        action: 'candidate',
                        candidate: event.candidate
                    })
                }
            }
            console.log('Created RTCPeerConnnection');

            const ws = new WebSocket('ws://192.168.100.10:8100')

            ws.onopen = () => {
                console.log('Connected to the signaling server')
            }

            ws.onerror = err => {
                console.error(err)
            }

            ws.onmessage = msg => {
                console.log('Got message', msg.data)
                const data = JSON.parse(msg.data)
                switch (data.action) {
                    case 'call':
                        break;
                    case 'offer':
                        let { offer } = data;
                        connection.setRemoteDescription(new RTCSessionDescription(offer))
                        connection.createAnswer(
                            answer => {
                                connection.setLocalDescription(answer)
                                sendMessage({ action: "answer", answer: answer })
                            },
                            error => {
                                alert('Error when creating an answer')
                                console.error(error)
                            }
                        )
                        break;
                    case 'answer':
                        let { answer } = data;
                        connection.setRemoteDescription(new RTCSessionDescription(answer))
                        break;
                    case 'candidate':
                        connection.addIceCandidate(new RTCIceCandidate(data.candidate))
                        break;
                    default:
                        break;
                }
            }

            sendMessage = message => {
                console.log('sendMessage', message);
                ws.send(JSON.stringify(message))
            }

            document.getElementById('call').addEventListener('click', async (e) => {
                connection.createOffer(
                    offer => {
                        connection.setLocalDescription(offer)
                        console.log('createOffer', offer);
                        sendMessage({ action: "offer", offer: offer });
                    },
                    error => {
                        alert('Error when creating an offer')
                        console.error(error)
                    }
                )
            });

        }
    </script>
</head>

<body>
    <button id="start">Start streaming</button>
    <button id="stop">Stop streaming</button>
    <button id="call">Call</button>
    <button id="hangup">Hang Up</button>
    <p></p>
    me:
    <video id="local_video" autoplay style="background-color: blue;">Start streaming</video>
    <p></p>
    other:
    <video id="remote_video" autoplay style="background-color: blueviolet;"></video>
</body>

</html>